package org.hepeng.workx.spring.security.web.handler;


import org.apache.commons.lang3.StringUtils;
import org.hepeng.workx.spring.security.web.savedrequest.OriginalRequestUrlHttpSessionRequestCache;
import org.hepeng.workx.spring.security.web.savedrequest.OriginalRequestUrlSavedRequest;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.security.web.savedrequest.SavedRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

/**
 * @author he peng
 */
public class RedirectOriginalRequestUrlAuthSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {

    private static final RequestCache REQUEST_CACHE = new OriginalRequestUrlHttpSessionRequestCache();

    @Override
    protected String determineTargetUrl(HttpServletRequest request, HttpServletResponse response) {

        if (isAlwaysUseDefaultTargetUrl()) {
            return super.getDefaultTargetUrl();
        }

        SavedRequest savedRequest = REQUEST_CACHE.getRequest(request, response);
        if (Objects.isNull(savedRequest) ||
                !(savedRequest instanceof OriginalRequestUrlSavedRequest)) {
            return super.getDefaultTargetUrl();
        }

        OriginalRequestUrlSavedRequest originalRequestUrlSavedRequest = (OriginalRequestUrlSavedRequest) savedRequest;
        String targetUrl;
        Object originalRequestUrl = originalRequestUrlSavedRequest.getOriginalRequestUrl();
        if (originalRequestUrl == null || StringUtils.isBlank(originalRequestUrl.toString())) {
            targetUrl = super.getDefaultTargetUrl();
        } else {
            targetUrl = originalRequestUrl.toString();
        }
        return targetUrl;
    }
}
